<template>
  <div class="user-data">
    <div class="user-data-top">
      <el-row class="clearfix" :gutter="30">
        <el-col :sm="24" :md="5" :lg="5">
          <div class="chart-box chart-box-border">
            <angle-arrow></angle-arrow>
            <data-title title="用户数据"></data-title>
            <div class="date-types">
              <ul>
                <li
                  v-for="(data, index) in dataTypes"
                  :key="index"
                  :class="{ active: dataTypesIndex == index }"
                  @click="choseDateType(index)"
                >
                  {{ data }}
                </li>
              </ul>
            </div>
            <ul class="user-data">
              <li v-for="(data, index) in userDataTop.statistics" :key="index">
                <p>{{ data.key }}</p>
                <i-count-up
                  :start="0"
                  :endVal="data.value"
                  :decimals="5"
                  :duration="2.5"
                  v-if="index != 4"
                ></i-count-up>
                <span v-else>
                  <em
                    v-if="
                      (
                        (userDataTop.statistics[1].value /
                          userDataTop.statistics[2].value) *
                        100
                      ).toFixed(2) != 'NaN'
                    "
                  >
                    {{
                      (
                        (userDataTop.statistics[1].value /
                          userDataTop.statistics[2].value) *
                        100
                      ).toFixed(2)
                    }}%
                  </em>
                  <em v-else>0%</em>
                </span>
              </li>
            </ul>
          </div>
        </el-col>
        <el-col :sm="24" :md="7" :lg="7">
          <div class="chart-box chart-box-border">
            <angle-arrow></angle-arrow>
            <data-title title="页面数据"></data-title>
            <div class="chart-select">
              <el-select
                v-model="form1.year"
                @change="choseDatesType($event, 1)"
              >
                <el-option
                  v-for="(data, index) in pageDateData"
                  :key="index"
                  :value="data.value"
                  :label="data.label"
                  >{{ data.label }}</el-option
                >
              </el-select>
            </div>
            <across-pillar
              :yAxisData="pageyAxisData"
              :yAxisName="''"
              :arrData="pageAxisData"
              left="60px"
              right="20px"
              bottom="0"
              top="20px"
              height="calc(100% - 80px)"
            >
            </across-pillar>
          </div>
        </el-col>
        <el-col :sm="24" :md="12" :lg="12">
          <div class="chart-box chart-box-border pv">
            <angle-arrow></angle-arrow>
            <data-title title="PV量和UV量"></data-title>
            <div class="chart-select">
              <el-date-picker
                v-model="form2.year"
                type="month"
                placeholder="选择年月"
                @change="changeDateMonth($event, 2)"
                format="yyyy-MM"
                value-format="yyyy-MM"
                :clearable="false"
                popper-class="chart-data-select"
              >
              </el-date-picker>
              <div class="chart-datetype">
                <ul>
                  <li
                    :class="{ active: pvDataIndex == index }"
                    v-for="(data, index) in Dates.dataTypes"
                    :key="index"
                    @click="choseDatesType(index, 2)"
                  >
                    {{ data.label }}
                  </li>
                </ul>
              </div>
            </div>
            <double-pillar
              :title="PVUVtitle"
              :series="PVUV"
              :dataAxis="PVUVAxis"
              height="calc(100% - 92px)"
            >
            </double-pillar>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="user-data-bottom">
      <el-row class="clearfix" :gutter="30">
        <el-col :sm="24" :md="12" :lg="12">
          <div class="chart-box chart-box-border time-data">
            <angle-arrow></angle-arrow>
            <data-title title="实时记录"></data-title>
            <div class="more" style="text-align: right">
              <a href="javascript:void(0);" style="color: #fff" @click="more"
                >查看更多</a
              >
            </div>
            <table-data :list="browseList" :step="0.5">
              <tr slot="table-head">
                <td
                  :width="browseWidthList[index]"
                  v-for="(item, index) in browseHeadList"
                  :key="index"
                >
                  <span>{{ item.text }}</span>
                </td>
              </tr>
              <div class="table-list" slot="table-list">
                <div
                  class="table-rwo"
                  v-for="(item, index) in browseList"
                  :key="index"
                >
                  <div :style="{ width: browseWidthList[0] }">
                    <span>{{ index + 1 }}</span>
                  </div>
                  <div :style="{ width: browseWidthList[1] }">
                    <span>{{ item.where }}</span>
                  </div>
                  <div :style="{ width: browseWidthList[2] }">
                    <span>{{ item.sum }}</span>
                  </div>
                  <div :style="{ width: browseWidthList[3] }">
                    <span>{{ item.num }}</span>
                  </div>
                  <div :style="{ width: browseWidthList[4] }">
                    <span>{{ item.add_num }}</span>
                  </div>
                  <div :style="{ width: browseWidthList[5] }">
                    <span>{{ item.add_num_rate }}%</span>
                  </div>
                </div>
              </div>
            </table-data>
          </div>
        </el-col>
        <el-col :sm="24" :md="12" :lg="12">
          <div class="chart-box chart-box-border line-num">
            <angle-arrow></angle-arrow>
            <data-title title="在线人数"></data-title>
            <line-chart
              :title="userDataTop.title"
              :series="userDataTop.series"
              ref="lineChart"
            >
            </line-chart>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import Dates from "@/statistics/dates.json";
import ICountUp from "vue-countup-v2";
import angleArrow from "@/statistics/components/angle-arrow.vue";
import dataTitle from "@/statistics/components/data-title.vue";
import tableData from "@/statistics/components/map/table-data.vue";
import doublePillar from "@/statistics/components/double-pillar.vue";
import lineChart from "@/statistics/components/line-chart.vue";
import { Loading } from "element-ui";
import recordTable from "./record-table.vue";
import acrossPillar from "../../components/across-pillar.vue";
export default {
  data() {
    return {
      Dates: Dates,
      dataTypes: [
        "今日",
        "昨日",
        "本周",
        "上周",
        "本月",
        "上月",
        "今年",
        "去年",
      ],
      dataTypesIndex: 0,
      userDataTop: {
        title: ["今日在线人数", "昨日在线人数"],
        series: [],
        statistics: [
          {
            key: "每日PV量",
            value: 0,
          },
          {
            key: "每日UV量",
            value: 0,
          },
          {
            key: "用户总数",
            value: 0,
          },
          {
            key: "用户增长数",
            value: 0,
          },
          {
            key: "用户活跃率",
            value: 0,
          },
        ],
      },
      browseHeadList: [
        {
          id: 0,
          text: "序号",
        },
        {
          id: 1,
          text: "页面",
        },
        {
          id: 2,
          text: "浏览数",
        },
        {
          id: 3,
          text: "用户量",
        },
        {
          id: 4,
          text: "横向增长",
        },
        {
          id: 5,
          text: "横向增长百分比",
        },
      ], //实时浏览记录头部
      browseWidthList: ["12.5%", "25%", "17.5%", "15%", "15%", "15%"], //实时浏览记录宽度
      browseList: [], //实时数据
      orderTitle: ["今日在线人数", "昨日在线人数"],
      order: [],
      orderAxis: [],
      onLineData: {
        title: ["页面数据"],
        series: [],
      },
      // PV/UV数据
      pvDataIndex: 1,
      form2: {
        year: new Date(new Date()).Format("yyyy-MM"),
      },
      PVUVtitle: ["PV/百", "UV/个"],
      PVUV: [],
      PVUVAxis: [],
      // 页面访问数据
      form1: {
        year: "today",
      },
      pageDateData: [
        {
          label: "今日",
          value: "today",
        },
        {
          label: "昨日",
          value: "yesterday",
        },
        {
          label: "本周",
          value: "week",
        },
        {
          label: "上周",
          value: "lastWeek",
        },
        {
          label: "本月",
          value: "month",
        },
        {
          label: "上月",
          value: "lastMonth",
        },
        {
          label: "今年",
          value: "year",
        },
        {
          label: "去年",
          value: "lastYear",
        },
      ],
      pageyAxisData: [],
      pageAxisData: [],
      layerIndex: null,
    };
  },
  methods: {
    init() {
      this.getUserDataTop("today");
      this.getUserPuData(3, "pvuv");
      this.getUserPageData();
      this.getUserPageData1();
    },
    // 用户数据&在线人数
    getUserDataTop(time) {
      let loadingInstance = Loading.service({
        text: "加载中",
        background: "rgba(255,255,255,.1)",
      });
      this.$http(this.$ptApiList.UserDataTop, { time: time }).then((res) => {
        loadingInstance.close();
        let todayObj = {
          name: "今日在线人数",
          data: [],
          type: "line",
          itemStyle: {
            color: "#f9764c",
          },
          lineStyle: {
            width: 3,
          },
        };
        let yestodayObj = {
          name: "昨日在线人数",
          data: [],
          type: "line",
          itemStyle: {
            color: "#00fbfc",
          },
          lineStyle: {
            width: 3,
          },
        };
        res.datas.online_today.forEach((item) => {
          todayObj.data.push(item.num);
        });
        res.datas.online_yesterday.forEach((item) => {
          yestodayObj.data.push(item.num);
        });
        this.userDataTop.series.push(todayObj, yestodayObj);
        this.userDataTop.statistics[0].value = res.datas.statistics.pv;
        this.userDataTop.statistics[1].value = res.datas.statistics.uv;
        this.userDataTop.statistics[2].value = res.datas.statistics.allUserNum;
        this.userDataTop.statistics[3].value = res.datas.statistics.addUserNum;
        this.userDataTop.statistics[4].value =
          res.datas.statistics.userOnlieNum;
      });
    },
    choseDateType(index) {
      let time = "";
      switch (index) {
        case 0:
          time = "today";
          break;
        case 1:
          time = "yestoday";
          break;
        case 2:
          time = "week";
          break;
        case 3:
          time = "lastWeek";
          break;
        case 4:
          time = "month";
          break;
        case 5:
          time = "lastMonth";
          break;
        case 6:
          time = "year";
          break;
        case 7:
          time = "lastYear";
          break;
      }
      this.dataTypesIndex = index;
      this.getUserDataTop(time);
    },
    // PV用户量/ UV浏览量
    getUserPuData(type, colum) {
      let data = {};
      let yearDate,
        year,
        month,
        today,
        days = [];
      if (colum === "pvuv") {
        yearDate = new Date(Date.parse(this.form2.year));
        year = yearDate.getFullYear();
        month = yearDate.getMonth() + 1;
        today = new Date(new Date()).Format("d");
        let currentYear = new Date().getFullYear();
        let currentMonth = new Date().getMonth() + 1;
        let dayCount;
        if (currentYear == year && currentMonth == month) {
          dayCount = today;
        } else {
          dayCount = this.getDaysInMonth(year, month);
        }
        for (var i = 0; i < dayCount; i++) {
          days.push(i + 1 + "日");
        }
        data = {
          type: type,
          time: this.form2.year,
          page_type: 1,
          limit: 12,
          page: 0,
        };
      }
      if (this.pvDataIndex == 1) {
        data.limit = this.getDaysInMonth(year, month) + 1;
      }
      let loadingInstance = Loading.service({
        text: "加载中",
        background: "rgba(255,255,255,.1)",
      });
      this.$http(this.$ptApiList.UserPuData, data).then((res) => {
        loadingInstance.close();
        if (colum === "pvuv") {
          if (res.datas.uv.length || res.datas.pv.length) {
            if (this.pvDataIndex == 0) {
              this.PVUVAxis = [
                "1月",
                "2月",
                "3月",
                "4月",
                "5月",
                "6月",
                "7月",
                "8月",
                "9月",
                "10月",
                "11月",
                "12月",
              ];
            } else {
              this.PVUVAxis = days;
            }
            let uvObj = {
              data: [],
              name: "UV/个",
              type: "bar",
              itemStyle: {
                color: "#067add",
              },
              itemStyleArray: [
                {
                  offset: 0,
                  color: "#fff",
                },
                {
                  offset: 0.2,
                  color: "#067add",
                },
                {
                  offset: 1,
                  color: "transparent",
                },
              ],
            };
            let pvObj = {
              data: [],
              name: "PV/百",
              type: "bar",
              itemStyle: {
                color: "#f9764c",
              },
              itemStyleArray: [
                {
                  offset: 0,
                  color: "#fff",
                },
                {
                  offset: 0.2,
                  color: "#f9764c",
                },
                {
                  offset: 1,
                  color: "transparent",
                },
              ],
            };
            // res.datas.uv.forEach(item => {
            // 	uvObj.data.push(item.count)
            // })
            // res.datas.pv.forEach(item => {
            // 	pvObj.data.push((item.num / 100).toFixed(2))
            // })
            let startMonth = 1;
            if (res.datas.uv) {
              res.datas.uv.forEach((item, index) => {
                if (index == 0) {
                  startMonth = item.add_time - 1;
                }
                for (let i = 0; i < startMonth; i++) {
                  uvObj.data[i] = 0;
                }
                uvObj.data.push(item.count);
              });
            }
            if (res.datas.pv.length) {
              res.datas.pv.forEach((item, index) => {
                if (index == 0) {
                  startMonth = item.add_time - 1;
                }
                for (let i = 0; i < startMonth; i++) {
                  pvObj.data[i] = 0;
                }
                pvObj.data.push((item.num / 100).toFixed(2));
              });
            }
            this.PVUV.push(pvObj, uvObj);
          } else if (!res.datas.uv.length && !res.datas.pv.length) {
            if (this.pvDataIndex == 0) {
              this.$confirm(year + "年没有数据，请重新选择", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                showCancelButton: false,
              }).then(() => {});
            } else if (this.pvDataIndex == 1) {
              this.$confirm(
                year + "-" + month + "月没有数据，请重新选择",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                  showCancelButton: false,
                }
              ).then(() => {});
            }
          }
        }
      });
    },
    // 获取某年某月所有天数
    getDaysInMonth(year, month) {
      month = parseInt(month, 10);
      var temp = new Date(year, month, 0);
      return temp.getDate();
    },
    // 选择年月
    changeDateMonth(e, index) {
      switch (index) {
        case 1:
          this.pageyAxisData = [];
          this.pageAxisData = [];
          this.getUserPageData();
          break;
        case 2:
          this.PVUVAxis = [];
          this.PVUV = [];
          if (this.pvDataIndex == 0) {
            this.getUserPuData(2, "pvuv");
          } else {
            this.getUserPuData(3, "pvuv");
          }
          break;
        case 3:
          this.order = [];
          this.orderAxis = [];
          if (this.orderDataIndex == 0) {
            this.getStoreDataTable(2);
          } else {
            this.getStoreDataTable(3);
          }
          break;
      }
    },
    // 选择日期类型
    choseDatesType(e, index) {
      switch (index) {
        case 1:
          this.pageyAxisData = [];
          this.pageAxisData = [];
          this.getUserPageData1();
          break;
        case 2:
          this.pvDataIndex = e;
          this.PVUVAxis = [];
          this.PVUV = [];
          if (e == 0) {
            this.getUserPuData(2, "pvuv");
          } else {
            this.getUserPuData(3, "pvuv");
          }
          break;
        case 3:
          this.orderDataIndex = e;
          this.order = [];
          this.orderAxis = [];
          if (e == 0) {
            this.getStoreDataTable(2);
          } else {
            this.getStoreDataTable(3);
          }
          break;
      }
    },
    // 获取页面访问实时记录
    getUserPageData() {
      let data = {
        type: 3,
        time: "today",
        page_type: 1,
        limit: 20,
        page: 0,
      };
      this.$http(this.$ptApiList.UserPageTable, data).then((res) => {
        this.browseList = res.datas;
      });
    },
    more() {
      this.layerIndex = this.$layer.iframe({
        content: {
          content: recordTable, //传递的组件对象
          parent: this, //当前的vue对象
          data: {}, //props
        },
        area: ["70%", "60%"],
        title: "实时浏览记录",
        maxmin: true,
        cancel: () => {},
      });
    },
    // 页面访问数据
    getUserPageData1() {
      let data = {};
      let yearDate,
        year,
        month,
        days = [];
      yearDate = new Date(Date.parse(this.form2.year));
      year = yearDate.getFullYear();
      month = yearDate.getMonth() + 1;
      for (var i = 0; i < this.getDaysInMonth(year, month); i++) {
        days.push(i + 1 + "日");
      }
      data = {
        time: this.form1.year,
        page_type: 1,
        limit: 20,
        page: 0,
      };
      let loadingInstance = Loading.service({
        background: "rgba(255,255,255,.1)",
        text: "加载中",
      });
      this.$http(this.$ptApiList.UserPageData, data).then((res) => {
        loadingInstance.close();
        let pageUv = {
          data: [],
          name: "访问次数",
          type: "bar",
          label: {
            show: true,
            position: "right",
            color: "#FFF",
            fontSize: 10,
            formatter: "{c} 次",
          },
          itemStyle: {
            color: "#067cde",
          },
        };
        let pageUvData = [];
        let pageyAxisData = [];
        if (res.datas.img.length) {
          res.datas.img.forEach((item) => {
            let name = item.where.split("-");
            pageUvData.push(item.count);
            pageyAxisData.push(item.where.slice(0, 5));
          });
          pageUv.data = pageUvData.reverse();
          this.pageyAxisData = pageyAxisData.reverse();
          this.pageAxisData.push(pageUv);
        }
      });
    },
    // 计算整点进行请求数据
    initTime() {
      let time = 60 - new Date().getSeconds(); //获取距离整分时剩的秒数
      const timer = setTimeout(() => {
        time = 60;
        let minutes = new Date().getMinutes();
        if (minutes == 0) {
          this.initData();
        }
        // 每一分钟执行一次
        const timer2 = setInterval(() => {
          let minutes = new Date().getMinutes();
          if (minutes == 0) {
            this.initData();
          }
        }, time * 1000);
        // 页面销毁清除每分钟的定时器
        this.$once("hook:beforeDestroy", () => {
          clearInterval(timer2);
        });
        // 清除第一个定时器
        clearTimeout(timer);
      }, time * 1000);
      // 以防快速刷新时没清除定时器
      this.$once("hook:beforeDestroy", () => {
        clearTimeout(timer);
      });
    },
    // 清除数据
    initData() {
      this.form1.year = "today";
      this.dataTypesIndex = 0;
      this.userDataTop.series = [];
      this.pvDataIndex = 1;
      this.PVUV = [];
      this.browseList = [];
      this.pageyAxisData = [];
      this.pageAxisData = [];
      this.form2.year = new Date(new Date()).Format("yyyy-MM");
      this.$layer.close(this.layerIndex);
      this.init();
    },
  },
  components: {
    angleArrow,
    ICountUp,
    dataTitle,
    tableData,
    doublePillar,
    lineChart,
    acrossPillar,
  },
  mounted() {
    this.init();
    this.initTime();
  },
};
</script>

<style lang="scss" scoped>
.user-data {
  .chart-select {
    display: flex;
    align-items: center;
    position: relative;
    z-index: 10;
    /deep/ .el-date-editor,
    /deep/ .el-select {
      width: 120px;
      &:nth-child(n + 1) {
        margin-left: 10px;
      }
      .el-input__inner {
        height: 32px;
        line-height: 32px;
        border-color: #02688e;
        background-color: #022672;
        color: #fff;
        &::-webkit-input-placeholder {
          color: #fff !important;
        }
      }
      .el-input__icon {
        line-height: 32px;
        color: #fff !important;
      }
    }
  }
  .chart-datetype {
    margin-left: 10px;
    ul {
      display: flex;
      align-items: center;
      border: solid 1px #02688e;
      border-radius: 5px;
      background-color: #022672;
      overflow: hidden;
      li {
        color: #fff;
        height: 32px;
        line-height: 32px;
        padding: 0 10px;
        cursor: pointer;
        &:first-child {
          border-right: solid 1px #02688e;
        }
        &.active {
          background-color: #00fbfc;
          color: #141414;
        }
      }
    }
  }
  .chart-box {
    position: relative;
    height: 100%;
    padding: 10px;
    border-radius: 5px;
    &::before,
    &::after {
      content: " ";
      position: absolute;
      top: 0;
      left: 50%;
      width: 199px;
      height: 2px;
      transform: translateX(-50%);
      background: url("../../../assets/data-images/tabs-light.png");
    }
    &::after {
      top: initial;
      bottom: 0;
    }
  }
  .clearfix {
    height: 100%;
    .el-col {
      height: 100%;
    }
  }
  .chart-box-border {
    border: solid 1px rgba(0, 255, 255, 0.3);
    box-shadow: 0 0 15px rgba(0, 252, 252, 0.3) inset;
  }
  .user-data-top {
    position: absolute;
    left: 25px;
    right: 25px;
    top: 25px;
    height: calc(50% - 25px);
    .date-types {
      margin: 0 auto;
      width: 85%;
      height: 22px;
      line-height: 20px;
      border: solid 1px #277c9a;
      border-radius: 5px;
      position: relative;
      overflow: hidden;
      ul {
        display: flex;
        align-items: center;
        li {
          position: relative;
          flex: 1;
          text-align: center;
          cursor: pointer;
          color: #fff;
          position: relative;
          z-index: 2;
          font-size: 12px;
          transition: all 0.2s;
          &.active {
            color: #030e39;
            background-color: #00fbfc;
            &::after {
              background-color: #00fbfc;
            }
          }
          &::after {
            content: "";
            position: absolute;
            top: 50%;
            right: 0;
            transform: translateY(-50%);
            width: 1px;
            height: 10px;
            background-color: #277c9a;
          }
          &:last-child {
            &::after {
              width: 0px;
            }
          }
        }
      }
    }
    .user-data {
      margin-top: 20px;
      margin-left: 30px;
      height: calc(100% - 70px);
      display: flex;
      flex-wrap: wrap;
      li {
        width: calc((100% - 65px) / 2);
        height: calc((100% - 80px) / 3);
        border-radius: 5px;
        border: solid 1px #00ffff;
        box-shadow: 0 0 15px rgba(0, 252, 252, 0.9) inset;
        padding: 10px;
        margin-top: 10px;
        p {
          font-size: 14px;
          color: #fff;
        }
        span {
          font-size: 24px;
          font-weight: bold;
        }
        &:nth-child(1) span {
          color: #fdcf00;
        }
        &:nth-child(2) span {
          color: #00fbfc;
        }
        &:nth-child(3) span {
          color: #07eda6;
        }
        &:nth-child(4) span {
          color: #f9764c;
        }
        &:nth-child(5) span,
        &:nth-child(6) span {
          color: #7ebbff;
        }
        &:nth-child(2n) {
          margin-left: 30px;
        }
      }
    }
    .pv {
      /deep/ .data-title {
        position: relative;
        overflow: visible;
        &::before {
          content: " ";
          position: absolute;
          bottom: -35px;
          left: 50%;
          transform: translateX(-50%);
          background-image: url("../../../assets/data-images/merchant-line.png");
          background-size: 100% auto;
          background-repeat: no-repeat;
          z-index: 9;
          height: 32px;
          width: 80%;
        }
      }
      /deep/ .Page{
        box-shadow: none;
      }
    }
  }
  .user-data-bottom {
    position: absolute;
    left: 25px;
    right: 25px;
    bottom: 25px;
    height: calc(50% - 50px);
    margin-top: 25px;
    .line-num {
      /deep/ .data-title {
        position: relative;
        overflow: visible;
        &::before {
          content: " ";
          position: absolute;
          bottom: -35px;
          left: 50%;
          transform: translateX(-50%);
          background-image: url("../../../assets/data-images/merchant-line.png");
          background-size: 100% auto;
          background-repeat: no-repeat;
          z-index: 9;
          height: 32px;
          width: 80%;
        }
      }
      /deep/ .Page {
        box-shadow: none;
      }
      /deep/ .line-chart{
        box-shadow: none;
      }
    }
    .time-data {
      /deep/ .table-header {
        tr {
          background-color: #0e2f60;
        }
      }
    }
  }
}
</style>